package com.yangoxix.lovegoing.service;

import com.yangoxix.lovegoing.mapper.AuditPublisherMapper;
import com.yangoxix.lovegoing.mapper.UserMapper;
import com.yangoxix.lovegoing.pojo.AuditPublisher;
import org.springframework.stereotype.Service;

@Service
public class PublisherService {
    private static final int PUBLISHER_MASK = 2;
    private final UserMapper userMapper;
    private final AuditPublisherMapper auditPublisherMapper;

    public PublisherService(UserMapper userMapper, AuditPublisherMapper auditPublisherMapper) {
        this.userMapper = userMapper;
        this.auditPublisherMapper = auditPublisherMapper;
    }

    public boolean isPublisher(String userName) {
        if (!userMapper.isUserExisted(userName))
            return false;
        else
            return userMapper.selectMaskByUsername(userName) == PUBLISHER_MASK;
    }

    public void applyPublisher(String username, String reason) {
        AuditPublisher auditPublisher = new AuditPublisher();
        auditPublisher.setUsername(username);
        auditPublisher.setReason(reason);
        auditPublisherMapper.insert(auditPublisher);
    }

    public boolean isApplyExisted(String username) {
        return auditPublisherMapper.isAuditingByUsername(username);
    }

    public void auditAccept(String username) {
        removeApplyEntryOf(username);
        if (userMapper.isUserExisted(username)) {
            userMapper.updateMaskByUsername(username, PUBLISHER_MASK);
        }
    }

    public void auditDeny(String username) {
        removeApplyEntryOf(username);
    }

    private void removeApplyEntryOf(String username) {
        auditPublisherMapper.deleteById(username);
    }

}
